package com.ty.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogContent;
import com.aliyun.openservices.log.common.LogGroupData;
import com.aliyun.openservices.log.common.LogStore;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.BatchGetLogResponse;
import com.aliyun.openservices.log.response.CreateLogStoreResponse;
import com.aliyun.openservices.log.response.GetContextLogsResponse;
import com.aliyun.openservices.log.response.GetCursorResponse;
import com.aliyun.openservices.log.response.GetLogsResponse;

public class Test {


	private static int getCurrentTimestamp() {
        return (int) (new Date().getTime() / 1000);
    }

    private static class PackInfo {
        public String packID;
        public String packMeta;

        public PackInfo(String id, String meta) {
            this.packID = id;
            this.packMeta = meta;
        }
    }

    private static PackInfo extractPackInfo(QueriedLog log) {
        PackInfo ret = new PackInfo("", "");
        ArrayList<LogContent> contents = log.GetLogItem().GetLogContents();
        for (int i = 0; i < contents.size(); ++i) {
            LogContent content = contents.get(i);
            if (content.GetKey().equals("__tag__:__pack_id__")) {
                ret.packID = content.GetValue();
            } else if (content.GetKey().equals("__pack_meta__")) {
                ret.packMeta = content.GetValue();
            }
        }
        return ret;
    }

    public static void main(String args[]) throws InterruptedException, LogException {
    	

		String project = "klwxvideo";  //待创建的Project的名称。
		String logstore = "klwxvideo";     //待创建的Logstore的名称。
		
    	
    	String endpoint = "cn-beijing.log.aliyuncs.com"; // 选择与project所属区域匹配的Endpoint。
        String accessKeyId = "LTAI4G5B9NAWskR2fiZaSr77"; // 使用您的阿里云访问密钥AccessKeyId。
        String accessKeySecret = "6rC3aowKW7qqL44ATIgU8gFVJFOWiq"; // 使用您的阿里云访问密钥AccessKeySecret。
       
        // 构建一个客户端实例。
        Client client = new Client(endpoint, accessKeyId, accessKeySecret);

        System.out.println("请确保指定的logstore已开启索引");
        Thread.sleep(3000);

        // 使用GetLogs并在查询语句中加上| with_pack_meta来获取起始日志的pack_id和pack_meta。
        // 查询时间范围：最近15分钟。
        // 起始日志：返回结果的第一条。
        String query = "*|with_pack_meta";
        GetLogsResponse response = client.GetLogs(project, logstore,
                (int) getCurrentTimestamp() - 900, (int) getCurrentTimestamp(),
                "", query);
        ArrayList<QueriedLog> logs = response.GetLogs();
        if (logs.isEmpty()) {
            System.out.println("未查询到任何日志");
            System.exit(1);
        }

        // 提取第一条日志的pack信息。
        PackInfo info = extractPackInfo(logs.get(0));
        if (info.packMeta.isEmpty() || info.packID.isEmpty()) {
            System.out.println("pack ID: " + info.packID + ", pack meta: " + info.packMeta);
            System.out.println("起始日志的pack信息不完整，请确保该日志是通过logtail写入的");
            System.exit(1);
        }

        // 使用得到的pack信息进行上下文查询（双向查询）。
        GetContextLogsResponse contextRes = client.getContextLogs(project, logstore,
                info.packID, info.packMeta, 10, 10);
        System.out.println("双向查询");
        System.out.println("pack ID: " + info.packID + ", pack meta: " + info.packMeta);
        System.out.println("is complete: " + contextRes.isCompleted());
        System.out.println("total lines: " + contextRes.getTotalLines());
        System.out.println("back lines: " + contextRes.getBackLines());
        System.out.println("forward lines: " + contextRes.getForwardLines());
        Thread.sleep(1000);

        // 使用查询结果中的第一条日志，向前查询上文（单向），至多三次。
        List<QueriedLog> contextLogs = contextRes.getLogs();
        for (int i = 0; i < 3 && !contextLogs.isEmpty(); i++) {
            QueriedLog log = contextLogs.get(0);
            info = extractPackInfo(log);
            GetContextLogsResponse res = client.getContextLogs(project, logstore,
                    info.packID, info.packMeta, 10, 0);
            System.out.println("向前查询上文");
            System.out.println("pack ID: " + info.packID + ", pack meta: " + info.packMeta);
            System.out.println("is complete: " + res.isCompleted());
            System.out.println("total lines: " + res.getTotalLines());
            System.out.println("back lines: " + res.getBackLines());
            System.out.println("forward lines: " + res.getForwardLines());
            contextLogs = res.getLogs();

            Thread.sleep(1000);
        }

        // 使用查询结果中的最后一条日志，向后查询下文（单向），至多三次。
        contextLogs = contextRes.getLogs();
        for (int i = 0; i < 3 && !contextLogs.isEmpty(); i++) {
            QueriedLog log = contextLogs.get(contextLogs.size() - 1);
            info = extractPackInfo(log);
            GetContextLogsResponse res = client.getContextLogs(project, logstore,
                    info.packID, info.packMeta, 0, 10);
            System.out.println("向后查询下文");
            System.out.println("pack ID: " + info.packID + ", pack meta: " + info.packMeta);
            System.out.println("is complete: " + res.isCompleted());
            System.out.println("total lines: " + res.getTotalLines());
            System.out.println("back lines: " + res.getBackLines());
            System.out.println("forward lines: " + res.getForwardLines());
            contextLogs = res.getLogs();
   
           
        }
    }

}
